package com.yenlien.traceyun.breed.service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.breed.dao.BreedDao;
import com.yenlien.traceyun.breed.dao.BreedDetailDao;
import com.yenlien.traceyun.breed.entity.Breed;
import com.yenlien.traceyun.breed.entity.BreedDetail;
import com.yenlien.traceyun.webase.exception.BusinessException;

/**
 * @author master yi
 */
@Service
public class BreedService {
    @Autowired
    private BreedDao breedDao;
    @Autowired
    private BreedDetailDao breedDetailDao;
    @Autowired
    private JdbcTemplate jdbc;

    public Page<Breed> findByList(final Breed breed) {
        Pageable pageable = PageRequest.of(breed.getPage(), breed.getPageSize(), Sort.Direction.DESC, ("createtime"));
        return breedDao.findAll(new Specification<Breed>() {
            private static final long serialVersionUID = -1396496630802017658L;

            @Override
            public Predicate toPredicate(Root<Breed> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> breedName = root.get("breedName");
                Path<String> batch = root.get("batch");
                //构造查询条件
                List<Predicate> list = new ArrayList<Predicate>();
                Predicate[] predicateA = new Predicate[list.size()];
                Predicate predicateAnd = cb.and(list.toArray(predicateA));

                if (StringUtils.isNotEmpty(breed.getBreedName())) {
                    List<Predicate> list2 = new ArrayList<>();
                    if (!StringUtils.isEmpty(breed.getBreedName())) {
                        list2.add(cb.like(breedName, "%" + breed.getBreedName() + "%"));
                        list2.add(cb.like(batch, "%" + breed.getBatch() + "%"));
                    }
                    Predicate[] predicateO = new Predicate[list2.size()];
                    Predicate predicateOr = cb.or(list2.toArray(predicateO));
                    return query.where(predicateAnd, predicateOr).getRestriction();
                } else {
                    return predicateAnd;
                }
            }
        }, pageable);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public void save(Breed breed) {
        Breed b = breedDao.findByBatch(breed.getBatch());
        //修改
        if (StringUtils.isNotEmpty(breed.getId())) {
//            if(b!=null && !b.getId().equals(breed.getId())){
//				throw new BusinessException("A0001", "养殖批次号已存在，请修改后再提交");
//			}
            throw new BusinessException("A0001", "流程已定不支持修改");
        } else {//添加
            if (b != null) {
                throw new BusinessException("A0001", "养殖批次号已存在，请修改后再提交");
            }
        }

        breed.setSurplusNumber(breed.getBreedNumber());
        breed.setSource("养殖");
        breed.setLastStep(breed.getSoilId());
        breedDao.save(breed);

        //记录养殖详情
        List<BreedDetail> breedDetailList = breed.getBreedDetailList();
//        String sql = "insert into t_breed_detail (id,last_step,relevance_id,batch,seed_name,type,code,sex,equipment_id,equipment_name,source,time,is_out,company_id) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
//        List<Object[]> batchArgs = new ArrayList<Object[]>();
//        for (BreedDetail breedDetail : breedDetailList) {
//        	batchArgs.add(new Object[]{UUID.randomUUID().toString().replaceAll("-",""),breed.getLastStep(),breed.getId(),breed.getBatch(),breed.getSeedName(),breedDetail.getType(),
//        			breedDetail.getCode(),breedDetail.getSex(),breedDetail.getEquipmentId(),breedDetail.getEquipmentName(),"养殖",breedDetail.getTime(),0, UserAuthUtil.getLoginUser().getCompanyId()});
//        }
//        jdbc.batchUpdate(sql, batchArgs);
//		breedDetailDao.deleteByRelevanceId(breed.getId());
        if (breedDetailList != null && breedDetailList.size() > 0) {
            for (BreedDetail breedDetail : breedDetailList) {
                breedDetail.setRelevanceId(breed.getId());
                breedDetail.setBatch(breed.getBatch());
                breedDetail.setSeedName(breed.getSeedName());
                breedDetail.setSource(breed.getSource());
            }
            breedDetailDao.saveAll(breedDetailList);
        }

    }

    public Breed findById(String id) {
        Breed breed = breedDao.findById(id);
        if (breed == null) {
            throw new BusinessException("A0001", "数据有误");
        }
        breed.setBreedDetailList(breedDetailDao.findByRelevanceId(id));
        return breed;
    }

    public void bind(JSONObject params) {
        BreedDetail breedDetail = breedDetailDao.findByCode(params.getString("code"));
        if (breedDetail == null) {
            throw new BusinessException("A0001", "编号不存在");
        }
        breedDetail.setEquipmentId(params.getString("equipmentId"));
        breedDetail.setEquipmentName(params.getString("equipmentName"));
        breedDetailDao.save(breedDetail);
    }

    public List<JSONObject> findBatchSelect() {
        return breedDao.findAllBatch();
    }
}
